<template>
  <div class="tree-box personnel">
    <div class="left-box">
      <el-input
        class="filter-box"
        placeholder="输入关键字进行过滤"
        v-model="filterText">
        <!-- <section slot="append" v-if="$route.query.key">
          <el-button type="primary" size="mini" @click="showUploadDialog">批量导入</el-button>
        </section> -->
      </el-input>
      <section class="tree-box-height">
        <el-tree :data="treeData" 
                  accordion 
                  :props="defaultProps" 
                  ref="tree"
                  :filter-node-method="filterNode"
                  @node-click="handleNodeClick">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span class="tree-title">
              <i class="icon el-icon-s-shop" v-if="data.type == 1"></i>
              <i class="icon el-icon-s-custom" v-if="data.type == 3"></i>
              <span class="m-l-s">{{ data.name }}</span>
            </span>
            <span>
              <el-button class="tree-btn warning" 
                        type="text" 
                        size="mini" 
                        v-if="data.type == 1" 
                        @click.stop="editOrganization(data)">
                设置负责人
              </el-button>
              <el-button
                v-if="data.type == 1 && (!data.children || data.children == 0 || groupOrStation(data.children) == 'person')"
                class="tree-btn"
                type="text"
                size="mini"
                @click.stop="append(data, node)"
                >添加人员</el-button
              >
              <el-button v-if="data.type == 3" class="tree-btn danger" type="text" size="mini" @click.stop="disableBtn(data, node)">禁用</el-button>
              <!-- <el-button v-if="data.type == 3" class="tree-btn danger" type="text" size="mini" @click.stop="userCancel(data, node)">注销</el-button> -->
              <el-button v-if="data.type == 3" class="tree-btn danger" type="text" size="mini" @click.stop="deleteFn(data, node)">删除</el-button>
            </span>
          </span>
        </el-tree>
      </section>
    </div>
    <div class="right-box" v-if="showRight">
      <section class="right-header-box">人员信息</section>
      <el-form ref="form" :model="model" label-width="100px">
        <el-row class="row">
          <el-col :span="24">
            <el-form-item label="姓名" prop="employeeName" :rules="[{ required: true, message: '请输入姓名', trigger: 'blur' }]">
              <el-input maxlength="200" v-model="model.employeeName" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="手机号码"
              prop="mobile"
              :rules="[
                { required: true, message: '请输入手机号码', trigger: 'blur' },
                { pattern: /^1\d{10}$/, message: '请输入正确手机号', trigger: 'blur' },
              ]"
            >
              <el-input maxlength="11" v-model.number="model.mobile" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="原组织ID" prop="sourceKey">
              <el-input maxlength="200" v-model="model.sourceKey" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="员工类型" prop="type" :rules="[{ required: true, message: '请选择员工类型', trigger: '' }]">
              <el-select v-model="model.type" clearable>
                <el-option v-for="item in staffList" :key="item.primaryKey" :label="item.name" :value="item.primaryKey" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="岗位" prop="positionKeys" :rules="[{ required: true, message: '请选择岗位', trigger: '' }]">
              <el-select v-model="model.positionKeys" filterable clearable multiple collapse-tags>
                <el-option v-for="item in stationList" :key="item.primaryKey" :label="item.positionName" :value="item.primaryKey" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="技能标签" prop="tagKeys">
              <el-select v-model="model.tagKeys" filterable clearable multiple collapse-tags>
                <el-option v-for="item in skillList" :key="item.primaryKey" :label="item.name" :value="item.primaryKey" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-button size="small" type="primary" @click="save" class="default-button f-right">保存</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="right-box" v-if="showRightGroup">
      <section class="right-header-box">{{currentData.name}}</section>
      <el-form ref="formGroup" :model="modelOgz" label-width="120px">
        <el-row class="row">
          <el-col :span="24">
            <el-form-item label="负责人">
              <el-select class="full-width" clearable v-model="modelOgz.manager" filterable remote reserve-keyword placeholder="请搜索" :remote-method="remoteMethod" :loading="loading">
                <el-option v-for="item in userList" :key="item.primaryKey" :label="item.employeeName" :value="item.primaryKey"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-button size="small" type="primary" @click="save" class="default-button f-right">保存</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 批量导入dialog -->
    <el-dialog title="批量导入" :visible.sync="uploadDialog" width="60%" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="flex-box-start m-b-m align-items-center">
        <p class="left-lable">批量导入</p>
        <el-link :href="`/static/import.xlsx`">下载模板</el-link>
      </div>
      <div class="flex-box-start">
        <p class="left-lable m-t-xs">选择导入文件</p>
        <uploadFile v-if="otherData.enterpriseId" :is-multiple="false" filed-name="file" action="/business/oms/employ/import" :other-data="otherData" :max-size="20" accept-file-type=".xlsx,.xls,.csv" :file-list="fileList" @handleRemove="handleRemove" @handleSuccess="handleSuccess">
          <template v-slot:info>
            <div slot="tip" class="upload__tip m-l-s">支持格式：xls、xlsx、csv，单个文件不能超过20MB</div>
          </template>
        </uploadFile>
      </div>
      <div class="m-t-m">
        <div class="left-lable m-b-s">导入记录</div>
        <div class="record-item" v-for="(item, index) in recordList" :key="index">
          <span>{{ item.createTime | dateFormat('YYYY-MM-DD HH:mm:ss') }}&emsp;{{ item.behaviorDesc }}</span>
          <!-- <el-button class="normal-btn m-r-l" size="text" @click="downloadFile">查看</el-button> -->
        </div>
        <Pagination v-if="total > recordList.length" @change="pageChange" :total="total" />
      </div>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancleUpload">放弃添加</el-button>
        <el-button size="small" type="primary" @click="confirmUpload">提 交</el-button>
      </span> -->
    </el-dialog>
  </div>
</template>
<script>
  // tree中的节点类型:type => 1,组织 2,岗位 3,人员
  import * as Port from '../../../api';
  import { formValid } from '@/lib/utils';
  import { requestTips, askDialog } from '../../../assets/util';
  import uploadFile from './upload.vue';

  export default {
    data() {
      return {
        infoData: {},
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'name',
        },
        filterText: '',
        model: {
          employeeName: '',
          mobile: '',
          sourceKey: '',
          type: '',
          positionKeys: [],
          tagKeys: [],
        },
        skillList: [],
        stationList: [],
        staffList: [
          { primaryKey: '1', name: '自有' },
          { primaryKey: '2', name: '外包' },
        ],
        showRight: false,
        isEdit: false, //是否是编辑状态
        // 导入
        uploadDialog: false,
        recordList: [],
        fileList: [],
        otherData: {},
        currentPage: 1,
        pageSize: 10,
        total: 0,
        modelOgz: {
          primaryKey: '',
          manager: '',
          orgProjectType: ''
        },
        showRightGroup: false,
        loading:false,
        userList: []
      };
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    created() {
      // 获取默认的企业key
      if (!this.$route.query.key && localStorage.getItem('userEnterpriseid') && this.$route.query.isAdd != 1) {
        this.$route.query.key = localStorage.getItem('userEnterpriseid')
      }
    },
    mounted () {
      if (this.$route.query.key) {
        this.getData()
      }
    },
    components: { uploadFile },
    methods: {
      //数据源
      async getData() {
        if (this.$route.query.key) {
          let res = await Port.apiEnterpriseInfo(this.$route.query.key);
          this.infoData = res;
          this.otherData = {
            enterpriseId: res.key,
            structureCode: res.structureCode,
          };

          this.getInfo()
        }
      },
      // 导入
      showUploadDialog() {
        this.uploadDialog = true;
        this.getRecordList();
      },
      //导入记录
      async getRecordList(type) {
        let res = await Port.apiLog({
          pageSize: this.pageSize,
          currentPage: type ? this.currentPage : 1,
          targetType: 'import_employee',
          enterpriseid: this.infoData.key,
        });
        this.recordList = res.rows || [];
      },
      //移除文件
      handleRemove(file, fileList) {
        this.fileList.forEach((item, index) => {
          if (item.key == file.key) {
            this.fileList.splice(index, 1);
          }
        });
      },
      //上传成功
      handleSuccess(file, fileList) {
        if (file.data.success) {
          this.fileList.push({
            key: file.data.rows[0].key,
            url: file.data.rows[0].url,
            name: file.data.rows[0].name,
          });
          this.getRecordList();
        } else {
          this.fileList = [];
          this.$message.error(file.data.message);
        }
      },
      //取消导入
      cancleUpload() {
        this.uploadDialog = false;
        this.fileList = [];
      },
      //分页
      pageChange(e) {
        this.currentPage = e.currentPage;
        this.pageSize = e.pageSize;
        this.getRecordList('more');
      },
      // 过滤
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1 || (data.mobile && data.mobile.indexOf(value) !== -1);
      },
      //字典
      async getCommonData() {
        let res = await Port.apiTagList({
          enterpriseid: this.infoData.key,
          type: 'user_tag',
        });
        this.skillList = res.rows || [];
      },
      //岗位list
      async getStationList(key) {
        let res = await Port.apiJoList({ enterpriseid: this.infoData.key, organizationKey: key });
        this.stationList = res.rows || [];
      },
      //数据源
      async getInfo(type) {
        this.getCommonData();
        let res = await Port.apiOrganizationTree({
          enterpriseid: this.$route.query.key,
          rootPrimaryKey: this.infoData.structureCode,
          ifGetEmployee: true,
          isGetByNowLevel: this.$route.query.organizationKey ? true : false,
          primaryKey: this.$route.query.organizationKey || null
        });
        if (this.$route.query.organizationKey) {
          this.treeData = res.tree || [];
        } else {
          this.treeData = res.tree[0].children || [];
        }
        
        this.showRight = false;

        // 筛选
        this.$nextTick(() => {
          this.$refs.tree.filter(this.filterText);
        })
      },
      //控制右侧显隐
      controlRightHide (type) {
        let list = ["showRight","showRightGroup"]
        list.forEach(item=>{
          if (item != type) {
            this[item] = false
          }
        })
        this[type] = true
      },
      //编辑组织
      async editOrganization(data) {
        this.isEdit = true
        this.currentData = data
        let res = await Port.apiGroupInfo(data.key)
        this.remoteMethod(res.managerName)
        this.modelOgz.primaryKey = res.primaryKey
        this.modelOgz.manager = res.manager
        this.modelOgz.orgProjectType = res.orgProjectType
        this.controlRightHide('showRightGroup')
      },
      //搜索人
      async remoteMethod(e) {
        let res = await Port.apiUserList({
          enterpriseid:this.infoData.key,
          employeeName:e
        })
        this.userList = res.rows || []
      },
      //保存组织
      async saveGroupFn(){
        let param = {
          ...this.modelOgz
        }

        let res = await Port.apiGroupEdit(param)
        requestTips(res,()=>{
          this.getInfo()
        })
      },
      //保存人
      save() {
        if (this.showRight) {
          formValid(this, 'form', this.saveFn);
        } else if (this.showRightGroup){
          formValid(this, 'formGroup', this.saveGroupFn)
        }
      },
      async saveFn() {
        let param = {
          structureCode: this.infoData.structureCode,
          rootPrimaryKey: this.infoData.structureCode,
          enterpriseid: this.infoData.key,
          ...this.model,
        };
        param.type = Number(param.type);
        delete param.positionList;
        delete param.tagList;
        delete param.extend;
        param.orgKey = this.isEdit ? this.currentData.parentKey : this.currentData.key;
        let res = this.isEdit ? await Port.apiPersonEdit(param) : await Port.apiPersonAdd(param);
        requestTips(res, () => {
          this.getInfo();
        });
      },
      //新增人员
      append(data, node) {
        for (var i in this.model) {
          this.model[i] = '';
        }
        this.model.positionKeys = [];
        this.model.tagKeys = [];
        this.currentData = data;
        this.isEdit = false;
        this.controlRightHide("showRight")
        this.getStationList(data.key);
      },
      // 禁用
      disableBtn(data) {
        askDialog('是否禁用该员工？', async () => {
          const res = await Port.apiDimissionBan({ userKey: data.key });
          requestTips(res, () => {
            this.getInfo();
          });
        });
      },
      // 注销
      userCancel(data) {
        askDialog('是否注销？注销后将无法恢复，请谨慎操作！', async () => {
          const res = await Port.apiDimissionLogout({ userKey: data.key });
          requestTips(res, () => {
            this.getInfo();
          });
        });
      },
      //删除
      deleteFn(data) {
        askDialog('是否删除该人员？', async () => {
          const res = await Port.apiPersonDel({
            organizeKey: data.parentKey,
            employKey: data.key,
          });
          requestTips(res, () => {
            this.getInfo();
          });
        });
      },
      //人员详情
      async handleNodeClick(data) {
        if (data.type == 3) {
          this.currentData = data;
          this.getStationList(data.parentKey);
          this.isEdit = true;
          this.model = data;
          this.controlRightHide("showRight")
          let res = await Port.apiPersonInfo({
            orgKey: data.parentKey,
            enterpriseid: this.$route.query.key,
            employeeKey: data.key,
          });
          res.positionKeys = res.positionList;
          res.tagKeys = res.tagList;
          this.model = res;
          this.model.type = String(this.model.type);
        }
      },
      //判断是否能添加岗位或者组织
      groupOrStation(list) {
        let type = '';
        if (list && list.length > 0) {
          type = list[0].type == 3 ? 'person' : 'other';
        }
        return type;
      },
    },
  };
</script>
<style lang="scss" scoped>
  .personnel {
    position: relative;
    .btn-box {
      position: absolute;
      top: 20px;
      right: 20px;
    }
    .left-lable {
      width: 120px;
      font-size: 16px;
      font-weight: 550;
    }
    .record-item {
      padding-bottom: 10px;
    }
  }

  ::v-deep .el-tabs__header {
    padding: 15px 25px 0 25px;
  }

  .filter-box {
    margin-bottom: 15px;
  }

  .tree-box-height {
    height: calc(100vh - 160px);
    overflow: auto;
  }

  .tree-title {
    width: 100%;
  }

  .right-header-box {
    font-size: 18px;
    line-height: 50px;
    font-weight: bold;
  }
</style>
